'use client'

import { useState, useEffect, useCallback } from 'react'
import {
    Card,
    Row,
    Col,
    Button,
    Empty,
    Spin,
    message,
    Tag,
    Modal,
    Form,
    Popconfirm,
    Input,
    Select
} from 'antd'
import {
    AppstoreOutlined,
    EyeOutlined,
    EditOutlined,
    DeleteOutlined,
    ExclamationCircleOutlined
} from '@ant-design/icons'
import Link from 'next/link'
import { useRouter } from 'next/navigation'
import { useAuth } from '../../contexts/AuthContext'
import ProductSearchFilter from '../../components/ProductSearchFilter'

const { TextArea } = Input
const { Option } = Select

// 产品类型常量
const PRODUCT_TYPES = {
    WEBSITE: 'website',
    APP: 'app'
}

export default function MyProductsPage() {
    const [products, setProducts] = useState([])
    const [loading, setLoading] = useState(true)
    const [searchTerm, setSearchTerm] = useState('')
    const [filterType, setFilterType] = useState('all')
    const [editModalVisible, setEditModalVisible] = useState(false)
    const [editingProduct, setEditingProduct] = useState(null)
    const [editForm] = Form.useForm()
    const [deleteLoading, setDeleteLoading] = useState(false)

    const router = useRouter()
    const { user, isAuthenticated } = useAuth()

    // 检查用户认证状态
    useEffect(() => {
        if (!isAuthenticated) {
            message.warning('请先登录以查看您的产品')
            router.push('/login')
            return
        }
    }, [isAuthenticated, router])

    // 获取用户的产品列表
    const fetchMyProducts = useCallback(async () => {
        if (!isAuthenticated || !user?.id) {
            console.log('用户未认证或无用户ID:', { isAuthenticated, userId: user?.id })
            return
        }

        try {
            setLoading(true)
            console.log('正在获取用户产品，用户ID:', user.id)
            const response = await fetch(`/api/products?userId=${user.id}`)
            const data = await response.json()

            console.log('我的产品API响应:', data)

            if (data.success) {
                const productsData = Array.isArray(data.data?.products) ? data.data.products : []
                console.log('获取到的产品数据:', productsData)
                setProducts(productsData)
            } else {
                console.error('获取产品列表失败:', data.error)
                message.error('获取产品列表失败')
                setProducts([])
            }
        } catch (error) {
            console.error('获取我的产品列表错误:', error)
            message.error('网络错误，请稍后重试')
            setProducts([])
        } finally {
            setLoading(false)
        }
    }, [isAuthenticated, user?.id])

    useEffect(() => {
        if (isAuthenticated && user?.id) {
            fetchMyProducts()
        }
    }, [isAuthenticated, user?.id, fetchMyProducts])

    // 过滤产品
    const filteredProducts = Array.isArray(products) ? products.filter(product => {
        const matchesSearch = product.title?.toLowerCase().includes(searchTerm.toLowerCase()) ||
            product.description?.toLowerCase().includes(searchTerm.toLowerCase())
        const matchesType = filterType === 'all' || product.type === filterType
        return matchesSearch && matchesType
    }) : []

    // 获取产品类型标签颜色
    const getTypeColor = (type) => {
        switch (type) {
            case PRODUCT_TYPES.WEBSITE:
                return 'blue'
            case PRODUCT_TYPES.APP:
                return 'green'
            default:
                return 'default'
        }
    }

    // 获取产品类型显示名称
    const getTypeName = (type) => {
        switch (type) {
            case PRODUCT_TYPES.WEBSITE:
                return '网站'
            case PRODUCT_TYPES.APP:
                return '应用'
            default:
                return '未知'
        }
    }

    // 打开编辑模态框
    const handleEdit = (product) => {
        setEditingProduct(product)
        editForm.setFieldsValue({
            title: product.title,
            description: product.description,
            type: product.type,
            url: product.url
        })
        setEditModalVisible(true)
    }

    // 保存编辑
    const handleSaveEdit = async () => {
        try {
            const values = await editForm.validateFields()

            const response = await fetch(`/api/products/${editingProduct.id}`, {
                method: 'PUT',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify(values)
            })

            const result = await response.json()

            if (result.success) {
                message.success('产品信息更新成功')
                setEditModalVisible(false)
                setEditingProduct(null)
                editForm.resetFields()
                fetchMyProducts() // 重新获取产品列表
            } else {
                message.error(result.error?.message || '更新失败')
            }
        } catch (error) {
            console.error('更新产品错误:', error)
            message.error('更新失败，请稍后重试')
        }
    }

    // 删除产品
    const handleDelete = async (productId, productTitle) => {
        try {
            setDeleteLoading(true)

            const response = await fetch(`/api/products/${productId}`, {
                method: 'DELETE'
            })

            const result = await response.json()

            if (result.success) {
                message.success(`产品 "${productTitle}" 删除成功`)
                fetchMyProducts() // 重新获取产品列表
            } else {
                message.error(result.error?.message || '删除失败')
            }
        } catch (error) {
            console.error('删除产品错误:', error)
            message.error('删除失败，请稍后重试')
        } finally {
            setDeleteLoading(false)
        }
    }

    // 如果用户未认证，显示加载状态
    if (!isAuthenticated) {
        return (
            <div className="min-h-screen flex items-center justify-center">
                <Spin size="large" />
            </div>
        )
    }

    return (
        <div className="p-8">
            <div className="max-w-7xl mx-auto">
                {/* 页面标题 */}
                <div className="text-center mb-8">
                    <h1 className="text-3xl font-bold text-gray-900 mb-4">
                        <AppstoreOutlined className="mr-3" />
                        我的产品
                    </h1>
                    <p className="text-gray-600 text-lg">
                        管理您上传的所有产品，支持查询、编辑和删除操作
                    </p>
                </div>

                {/* 搜索和筛选 */}
                <ProductSearchFilter
                    searchTerm={searchTerm}
                    onSearchChange={setSearchTerm}
                    filterType={filterType}
                    onFilterChange={setFilterType}
                    resultCount={filteredProducts.length}
                    searchPlaceholder="搜索我的产品..."
                />

                {/* 产品列表 */}
                {loading ? (
                    <div className="text-center py-12">
                        <Spin size="large" />
                        <p className="mt-4 text-gray-500">加载中...</p>
                    </div>
                ) : filteredProducts.length === 0 ? (
                    <Empty
                        description={
                            searchTerm || filterType !== 'all'
                                ? "没有找到符合条件的产品"
                                : "您还没有上传任何产品，请使用Header中的上传模式来添加产品"
                        }
                        className="py-12"
                    />
                ) : (
                    <Row gutter={[24, 24]}>
                        {filteredProducts.map((product) => (
                            <Col xs={24} sm={12} lg={8} xl={6} key={product.id}>
                                <Card
                                    hoverable
                                    className="h-full"
                                    cover={
                                        product.thumbnail_url ? (
                                            <div className="h-48 overflow-hidden">
                                                {/* eslint-disable-next-line @next/next/no-img-element */}
                                                <img
                                                    alt={product.title}
                                                    src={product.thumbnail_url}
                                                    className="w-full h-full object-cover"
                                                />
                                            </div>
                                        ) : (
                                            <div className="h-48 bg-gray-100 flex items-center justify-center">
                                                <AppstoreOutlined className="text-4xl text-gray-400" />
                                            </div>
                                        )
                                    }
                                    actions={[
                                        <Link href={`/product/${product.id}`} key="view">
                                            <Button type="text" icon={<EyeOutlined />}>
                                                查看
                                            </Button>
                                        </Link>,
                                        <Button
                                            type="text"
                                            icon={<EditOutlined />}
                                            onClick={() => handleEdit(product)}
                                            key="edit"
                                        >
                                            编辑
                                        </Button>,
                                        <Popconfirm
                                            title="确认删除"
                                            description={`确定要删除产品 "${product.title}" 吗？此操作不可恢复。`}
                                            onConfirm={() => handleDelete(product.id, product.title)}
                                            okText="确认删除"
                                            cancelText="取消"
                                            okType="danger"
                                            icon={<ExclamationCircleOutlined style={{ color: 'red' }} />}
                                            key="delete"
                                        >
                                            <Button
                                                type="text"
                                                danger
                                                icon={<DeleteOutlined />}
                                                loading={deleteLoading}
                                            >
                                                删除
                                            </Button>
                                        </Popconfirm>
                                    ]}
                                >
                                    <Card.Meta
                                        title={
                                            <div className="flex items-center justify-between">
                                                <span className="truncate">{product.title}</span>
                                                <Tag color={getTypeColor(product.type)} className="ml-2">
                                                    {getTypeName(product.type)}
                                                </Tag>
                                            </div>
                                        }
                                        description={
                                            <div>
                                                <p className="text-gray-600 line-clamp-3 mb-2">
                                                    {product.description}
                                                </p>
                                                <div className="text-xs text-gray-400">
                                                    {new Date(product.created_at).toLocaleDateString('zh-CN')}
                                                </div>
                                            </div>
                                        }
                                    />
                                </Card>
                            </Col>
                        ))}
                    </Row>
                )}

                {/* 编辑产品模态框 */}
                <Modal
                    title="编辑产品信息"
                    open={editModalVisible}
                    onOk={handleSaveEdit}
                    onCancel={() => {
                        setEditModalVisible(false)
                        setEditingProduct(null)
                        editForm.resetFields()
                    }}
                    width={600}
                    okText="保存修改"
                    cancelText="取消"
                >
                    <Form
                        form={editForm}
                        layout="vertical"
                        className="mt-4"
                    >
                        <Form.Item
                            label="产品名称"
                            name="title"
                            rules={[
                                { required: true, message: '请输入产品名称' },
                                { max: 100, message: '产品名称不能超过100个字符' }
                            ]}
                        >
                            <Input placeholder="请输入产品名称" />
                        </Form.Item>

                        <Form.Item
                            label="产品描述"
                            name="description"
                            rules={[
                                { required: true, message: '请输入产品描述' },
                                { max: 1000, message: '产品描述不能超过1000个字符' }
                            ]}
                        >
                            <TextArea
                                rows={4}
                                placeholder="请详细描述您的产品功能、特点等..."
                                showCount
                                maxLength={1000}
                            />
                        </Form.Item>

                        <Form.Item
                            label="产品类型"
                            name="type"
                            rules={[{ required: true, message: '请选择产品类型' }]}
                        >
                            <Select placeholder="请选择产品类型">
                                <Option value={PRODUCT_TYPES.WEBSITE}>网站</Option>
                                <Option value={PRODUCT_TYPES.APP}>应用</Option>
                            </Select>
                        </Form.Item>

                        <Form.Item
                            label="访问地址"
                            name="url"
                            rules={[
                                { required: true, message: '请输入访问地址' },
                                { type: 'url', message: '请输入有效的URL地址' }
                            ]}
                        >
                            <Input placeholder="https://example.com" />
                        </Form.Item>
                    </Form>
                </Modal>
            </div>
        </div>
    )
}